/**
 * 判断是否是父节点
 * @param {Element} el
 * @param {Element} parentSelector
 * @returns
 */
export const matcheParentsEl = (el, parentSelector) => {
  let parent = el.parentElement;
  if (parent.matches(parentSelector)) {
    return parent;
  }
};

/**
 * 找元素的第n级父元素
 * @param {Element} ele
 * @param {Number} n
 * @returns
 */
export const findParents = (ele, n) => {
  while (ele && n) {
    ele = ele.parentElement ? ele.parentElement : ele.parentNode;
    n--;
  }
  return ele;
};

/**
 * 获取视口尺寸
 * @returns
 */
export const getViewportSize = () => {
  if (window.innerWidth) {
    return {
      w: window.innerWidth,
      h: window.innerHeight,
    };
  } else {
    // ie8及其以下
    if (document.compatMode === "BackCompat") {
      // 怪异模式
      return {
        w: document.body.clientWidth,
        h: document.body.clientHeight,
      };
    } else {
      // 标准模式
      return {
        w: document.documentElement.clientWidth,
        h: document.documentElement.clientHeight,
      };
    }
  }
};

/**
 * 获取滚动偏移量
 * @returns
 */
export const getScrollOffset = () => {
  if (window.pageXOffset) {
    return {
      x: window.pageXOffset,
      y: window.pageYOffset,
    };
  } else {
    return {
      x: document.body.scrollLeft + document.documentElement.scrollLeft,
      y: document.body.scrollTop + document.documentElement.scrollTop,
    };
  }
};

/**
 * 获取元素尺寸
 * @param {Element} el
 * @returns
 */
export const getElementSize = (el) => {
  const style = window.getComputedStyle(el);
  const width = el.offsetWidth;
  const height = el.offsetHeight;
  const paddingLeft = parseFloat(style.paddingLeft);
  const paddingRight = parseFloat(style.paddingRight);
  const paddingTop = parseFloat(style.paddingTop);
  const paddingBottom = parseFloat(style.paddingBottom);
  const borderLeft = parseFloat(style.borderLeftWidth);
  const borderRight = parseFloat(style.borderRightWidth);
  const borderTop = parseFloat(style.borderTopWidth);
  const borderBottom = parseFloat(style.borderBottomWidth);
  return {
    width: width - paddingLeft - paddingRight - borderLeft - borderRight,
    height: height - paddingTop - paddingBottom - borderTop - borderBottom,
  };
};
